import json
from django.http import JsonResponse
from app.static import NO_LOGIN
from .common import HttpError, HttpSuccess
from django.core.cache import cache


##修饰器内部函数执行顺序自上而下
##判断登录有没有过期
def checkLoginHandling(view_func):
    def wrapper(request, *args, **kwargs):
        token = request.META.get("HTTP_X_TOKEN", None)
        if token and cache.get(token):
            return view_func(request, *args, **kwargs)
        else:
            return JsonResponse(vars(HttpError(NO_LOGIN, "登录已过期，请重新登录")))

    return wrapper


##错误捕获
def errorHandling(view_func):
    def wrapper(request, *args, **kwargs):
        try:
            # 调用原始的视图函数
            return view_func(request, *args, **kwargs)
        except Exception as e:

            # 发生异常时返回错误信息
            error_message = str(e)
            return JsonResponse(vars(HttpError(msg=error_message)))

    return wrapper


##返回体json封装
def JsonResponse_res(view_func):
    def wrapper(request, *args, **kwargs):
        try:
            res = view_func(request, *args, **kwargs)
            ##如果返回值是JsonResponse，则直接返回
            if isinstance(res, JsonResponse):
                return res
            ##如果是错误，则返回错误http对象
            elif isinstance(res, Exception):
                return JsonResponse(vars(HttpError(msg=str(res))))
            ##其他类型的话用http包装一下
            elif isinstance(res, HttpSuccess) or isinstance(res, HttpError):
                return JsonResponse(vars(res))
            else:
                if type(res) != dict:
                    return JsonResponse(vars(HttpSuccess(data=vars(res))))
                else:
                    return JsonResponse(vars(HttpSuccess(data=res)))
        except Exception as e:
            return JsonResponse(vars(HttpError(msg=str(e))))

    return wrapper


##参数校验
def checkParams(params):
    def out(view_func):
        def wrapper(request, *args, **kwargs):
            json_data = json.loads(request.body)
            for param in params:
                if json_data.get(param) == None:
                    raise ValueError(f"缺少参数{param}")
            return view_func(request, *args, **kwargs)
        return wrapper
    return out
